﻿"use strict";
$jq.namespace('PeopleMedia');

PeopleMedia.CP = function () {
    var _sessionid = '00000000-0000-0000-0000-000000000000';
    var _theme = 0;
    var _domainName;
    var _subdomain;
    var _siteID;
    var _domainID;
    var _serverID;
    var _searchID;
    var _searchCategoryID;
    var _pinnedSearchID;
    var _pinnedSearchCategoryID;
    var _affiliateID;
    var _pageFolder;
    var _pagePath;
    var _pageVersion;
    var _sponsorID;
    var _visitorID;
    var _memberID;
    var _encodedMemberID;
    var _genderID;
    var _genderSeekID;
    var _cpServer;
    var _cpResourceRoot;
    var _postedForm = null;
    var _readyDelegate = new PeopleMedia.Delegate();
    var _ready = false;
    var _initComplete = false;
    var _initClientConfigComplete = false;
    var _initClientConfigError = null;
    var _stacktraceScriptLoaded = false;
    var _clientConfigDelegate = new PeopleMedia.Delegate();
    var _clientConfig = false;
    var _pmApiBaseUrl =  FRONT_SITE_URL+"registerfree/authorization";
    var _autologinEnabled = false;
    var _persistentLoginEnabled = false;
    var _genderSeekEnabled = false;
    var _invalidEmailDomainCheckEnabled = false;
    var _contentVersion = "";
    var _versionedContentRoot= "";
    var _useMaiLpsApi = false;
    var _defaultGenderID;
    var _defaultGenderSeekID;
    var _defaultMinAge;
    var _defaultMaxAge;
    var _defaultPostalCode;
    var _defaultEmailAddress;
    var _emailGuid;
    var _ajaxErrorMessage = "Whoops... something's amiss. Please try your request again. If you see this error repeatedly, please refresh the page.";

    var self = {
        Oid: "PeopleMedia.CP",
        SessionId: function (sessionid) {
            if (arguments.length > 0) {
                _sessionid = sessionid;
            } else {
                return _sessionid;
            }
        },

        Theme: function (theme) {
            if (arguments.length > 0) {
                _theme = theme;
            } else {
                return _theme;
            }
        },

        DomainName: function (domainName) {
            if (arguments.length > 0) {
                _domainName = domainName;
            } else {
                if (typeof (_domainName) === 'undefined' || _domainName === null || _domainName.length === 0) {
                    return PeopleMedia.Net.getDomainName();
                } else {
                    return _domainName;
                }
            }
        },

        Subdomain: function (subdomain) {
            if (arguments.length > 0) {
                _subdomain = subdomain;
            } else {
                if (typeof (_subdomain) === 'undefined' || _subdomain === null || _subdomain.length === 0) {
                    return "www";
                } else {
                    return _subdomain;
                }
            }
        },

        SiteID: function (siteID) {
            if (arguments.length > 0) {
                _siteID = siteID;
            } else {
                return _siteID;
            }
        },

        DomainID: function (domainID) {
            if (arguments.length > 0) {
                _domainID = domainID;
            } else {
                return _domainID;
            }
        },

        ServerID: function (serverID) {
            if (arguments.length > 0) {
                _serverID = serverID;
            } else {
                return _serverID;
            }
        },

        SearchID: function (searchID) {
            if (arguments.length > 0) {
                _searchID = searchID;
            } else {
                return _searchID;
            }
        },
        
        SearchCategoryID: function (searchCategoryID) {
            if (arguments.length > 0) {
                _searchCategoryID = searchCategoryID;
            } else {
                return _searchCategoryID;
            }
        },

        PinnedSearchID: function (pinnedSearchID) {
            if (arguments.length > 0) {
                _pinnedSearchID = pinnedSearchID;
            } else {
                return _pinnedSearchID;
            }
        },
        
        PinnedSearchCategoryID: function (pinnedSearchCategoryID) {
            if (arguments.length > 0) {
                _pinnedSearchCategoryID = pinnedSearchCategoryID;
            } else {
                return _pinnedSearchCategoryID;
            }
        },

        AffiliateID: function (affiliateID) {
            if (arguments.length > 0) {
                _affiliateID = affiliateID;
            } else {
                return _affiliateID;
            }
        },
        
        SponsorID: function (sponsorID) {
            if (arguments.length > 0) {
                _sponsorID = sponsorID;
            } else {
                return _sponsorID;
            }
        },

        VisitorID: function (visitorID) {
            if (arguments.length > 0) {
                _visitorID = visitorID;
            } else {
                return _visitorID;
            }
        },

        MemberID: function (memberID) {
            if (arguments.length > 0) {
                _memberID = memberID;
            } else {
                return _memberID;
            }
        },

        EncodedMemberID: function (encodedMemberID) {
            if (arguments.length > 0) {
                _encodedMemberID = encodedMemberID;
            } else {
                return _encodedMemberID;
            }
        },

        GenderID: function (genderID) {
            if (arguments.length > 0) {
                _genderID = genderID;
            } else {
                return _genderID;
            }
        },

        GenderSeekID: function (genderSeekID) {
            if (arguments.length > 0) {
                _genderSeekID = genderSeekID;
            } else {
                return _genderSeekID;
            }
        },        

        CpServer: function (cpServer) {
            if (arguments.length > 0) {
                _cpServer = cpServer;
            } else {
                return _cpServer;
            }
        },

        CpResourceRoot: function (cpResourceRoot) {
            if (arguments.length > 0) {
                _cpResourceRoot = cpResourceRoot;
            } else {
                return _cpResourceRoot;
            }
        },
        
        PageFolder: function (pageFolder) {
            if (arguments.length > 0) {
                _pageFolder = pageFolder;
            } else {
                return _pageFolder;
            }
        },
        
        PagePath: function (pagePath) {
            if (arguments.length > 0) {
                _pagePath = pagePath;
            } else {
                return _pagePath;
            }
        },

        PageVersion: function (pageVersion) {
            if (arguments.length > 0) {
                _pageVersion = pageVersion;
            } else {
                return _pageVersion;
            }
        },

        PostedForm: function (form) {
            if (arguments.length > 0) {
                _postedForm = form;
            } else {
                return _postedForm;
            }
        },

        getPMApiBaseUrl: function (pmApiBaseUrl) {
            if (typeof (pmApiBaseUrl) !== 'undefined' && pmApiBaseUrl !== null) {
                return _pmApiBaseUrl.replace("$METHOD$", pmApiBaseUrl);
            } else {
                return _pmApiBaseUrl;
            }
        },

        AutoLoginEnabled: function (autologinEnabled) {
            if (arguments.length > 0) {
                _autologinEnabled = autologinEnabled;
            } else {
                return _autologinEnabled;
            }
        },

        PersistentLoginEnabled: function (persistentLoginEnabled) {
            if (arguments.length > 0) {
                _persistentLoginEnabled = persistentLoginEnabled;
            } else {
                return _persistentLoginEnabled;
            }
        },
        
        GenderSeekEnabled: function (genderSeekEnabled) {
            if (arguments.length > 0) {
                _genderSeekEnabled = genderSeekEnabled;
            } else {
                return _genderSeekEnabled;
            }
        },
        InvalidEmailDomainCheckEnabled: function (invalidEmailDomainCheckEnabled) {
            if (arguments.length > 0) {
                _invalidEmailDomainCheckEnabled = invalidEmailDomainCheckEnabled;
            } else {
                return _invalidEmailDomainCheckEnabled;
            }
        },

        ContentVersion: function (contentVersion) {
            if (arguments.length > 0) {
                _contentVersion = contentVersion;
            } else {
                return _contentVersion;
            }
        },

        VersionedContentRoot: function (versionedContentRoot) {
            if (arguments.length > 0) {
                _versionedContentRoot = versionedContentRoot;
            } else {
                return _versionedContentRoot;
            }
        },

        SessionCookieName: function () {
            return "SSKY";
        },

        LpsApiUrl: function () {
            return "~/v3/lps/api";
        },

        UseMaiLpsApi: function (useMaiLpsApi) {
            if (arguments.length > 0) {
                _useMaiLpsApi = useMaiLpsApi;
            } else {
                return _useMaiLpsApi;
            }
        },

        DefaultGenderID: function (defaultGenderID) {
            if (arguments.length > 0) {
                this._defaultGenderID = this.convertGenderToID(defaultGenderID);
            } else {
                return this._defaultGenderID;
            }
        },

        DefaultGenderSeekID: function (defaultGenderSeekID) {
            if (arguments.length > 0) {
                this._defaultGenderSeekID = this.convertGenderToID(defaultGenderSeekID);
            } else {
                return this._defaultGenderSeekID;
            }
        },

        DefaultMinAge: function (defaultMinAge) {
            var age = null;
            if (arguments.length > 0) {
                if (typeof (defaultMinAge) !== 'undefined' && defaultMinAge !== null) {
                    age = parseInt(defaultMinAge, 10);
                    if (isNaN(age)) {
                        age = null;
                    }
                }
                this._defaultMinAge = age;
            } else {
                return this._defaultMinAge;
            }
        },

        DefaultMaxAge: function (defaultMaxAge) {
            var age = null;
            if (arguments.length > 0) {
                if (typeof (defaultMaxAge) !== 'undefined' && defaultMaxAge !== null) {
                    age = parseInt(defaultMaxAge, 10);
                    if (isNaN(age)) {
                        age = null;
                    }
                }
                this._defaultMaxAge = age;
            } else {
                return this._defaultMaxAge;
            }
        },

        DefaultPostalCode: function (defaultPostalCode) {
            if (arguments.length > 0) {
                this._defaultPostalCode = defaultPostalCode;
            } else {
                return this._defaultPostalCode;
            }
        },

        DefaultEmailAddress: function (defaultEmailAddress) {
            if (arguments.length > 0) {
                this._defaultEmailAddress = defaultEmailAddress;
            } else {
                return this._defaultEmailAddress;
            }
        },

        EmailGuid: function (emailGuid) {
            if (arguments.length > 0) {
                this._emailGuid = emailGuid;
            } else {
                return this._emailGuid;
            }
        },

        IsInitClientConfigComplete: function () {
            return _initClientConfigComplete;
        },

        AjaxErrorMessage: function() {
            return _ajaxErrorMessage;
        },

        isAjaxCancelled: function (jqXHR, textStatus, errorThrown) {
            try {
                // return true when user navigates away from the page by refreshing, clicking a link, or changing the URL in the browser
                return (errorThrown !== 'timeout' && (jqXHR.readyState === 0 || jqXHR.status === 0));
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "isAjaxCancelled" });
                return false;
            }
        },

        convertAjaxErrorToFault: function (jqXHR, textStatus, errorThrown) {
            var codeValue = "Ajax";
            var isCancelled = false;
            var reason = "Please try your request again.";
            try {
                codeValue = "Ajax" + ((typeof (errorThrown) !== 'undefined' && errorThrown !== null) ? (" " + errorThrown) : "");
                isCancelled = PeopleMedia.CP.isAjaxCancelled(jqXHR, textStatus, errorThrown);
                reason = PeopleMedia.CP.AjaxErrorMessage();
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "convertAjaxErrorToFault" });
            }
            return {
                "Code": codeValue,
                "Subcode": textStatus,
                "IsValid": false,
                "Fault": { "Code": { "Subcode": { "Value": { "Name": textStatus } }, "Value": { "Name": codeValue } }, "Reason": reason, "IsAjaxError": true, "IsCancelled": isCancelled },
                "IsCancelled": isCancelled,
                "jqXHR": jqXHR
            };
        },

        convertFaultToError: function (obj, field) {
            var errorObj = {};
            try {
                errorObj.IsAjaxError = (typeof (obj.IsAjaxError) !== 'undefined' && obj.IsAjaxError === true);
                errorObj.IsCancelled = (typeof (obj.IsCancelled) !== 'undefined' && obj.IsCancelled === true);
                if (obj) {
                    if (obj.Code) {
						//alert('code');
                        errorObj.Code = (obj.Code.Value && obj.Code.Value.Name) ? obj.Code.Value.Name : obj.Code;
                        if (obj.Code.Subcode && obj.Code.Subcode.Value && obj.Code.Subcode.Value.Name) {
                            errorObj.Subcode = obj.Code.Subcode.Value.Name;
                        }
                    }
                    if (obj.Subcode) {
						//alert('subcode');
                        errorObj.Subcode = obj.Subcode;
                    }
                    if (obj.Reason) {
						//alert('reason');
                        var reasonIsArray = (Array.isArray) ? Array.isArray(obj.Reason) : Object.prototype.toString.call(obj.Reason) === '[object Array]';
                        if (errorObj.IsCancelled) {
                            errorObj.Text = "";
                        } else {
                            errorObj.Text = (reasonIsArray) ? obj.Reason[0] : obj.Reason;
                        }
                    }
                    if (typeof (field) !== 'undefined' && field != null) {
						//alert('null');
                        errorObj.Field = field;
                    }
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "convertFaultToError" });
            }
            return errorObj;
        },

        getFirstError: function (errors) {
            try {
                var errorsIsArray = (Array.isArray) ? Array.isArray(errors) : Object.prototype.toString.call(errors) === '[object Array]';
                return (errorsIsArray) ? errors[0] : errors;
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "getFirstError" });
            }
        },

        init: function () {
            var thisObj = this;

            try {
                PeopleMedia.CP.initSessionValues();
                PeopleMedia.CP.initQueryStringValues();
                PeopleMedia.CP.ClientMessages = {
                    "RegHandle": "Please enter a username.",
                    "RegEmail": "Please enter an email address.",
                    "RegPassword": "Please enter a password.",
                    "RegCountryCode": "Please select a country.",
                    "RegPostalcode": "Please enter a valid zip/postal code.",
                    "RegCity": "Please enter a city.",
                    "RegState": "Please enter a state.",
                    "RegGender": "Please enter your gender.",
                    "RegBirthDay": "Please enter the Day of your birth.",
                    "RegBirthMonth": "Please enter the Month of your birth.",
                    "RegBirthYear": "Please enter the Year of your birth.",
                    "RegBirthGeneric": "Please enter your complete birthday.",
                    "RegBirthUnder18": "You must be past your 18th birthday to participate in this site.",
                    "RegTermsAndConditions": "You must agree to the Terms and Conditions.",
                    "LoginHandle": "Please enter your email address.",
                    "LoginPassword": "Please enter your password."
                };

                thisObj.initComplete();
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"init" });
            }
        },

        initSessionValues: function () {
            var sessionCookie = null;
            try {
                sessionCookie = PeopleMedia.Net.readCookie(PeopleMedia.CP.SessionCookieName());
                if (sessionCookie != null) {
                    var esid = sessionCookie['ESID'];
                    if (typeof (esid) !== 'undefined' && esid != null) {
                        PeopleMedia.CP.SessionId(esid);
                    }
                    var theme = sessionCookie['THEME'];
                    if (typeof (theme) !== 'undefined' && theme != null) {
                        PeopleMedia.CP.Theme(theme);
                    }
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initSessionValues", sessionCookie:sessionCookie });
            }
        },

        initQueryStringValues: function (currentQueryString) {
            try {
                var keyValues = PeopleMedia.Net.getQueryString(currentQueryString);
                var emailGuid = PeopleMedia.Net.getQueryStringValue(keyValues, "EmailGUID");
                if (typeof(emailGuid) !== 'undefined' && emailGuid !== null && emailGuid.length == 36) {
                    PeopleMedia.CP.EmailGuid(emailGuid);
                }
                var gender = PeopleMedia.Net.getQueryStringValue(keyValues, "iam");
                if (typeof (gender) !== 'undefined' && gender !== null && gender.length > 0) {
                    PeopleMedia.CP.DefaultGenderID(gender);
                }
                var genderSeek = PeopleMedia.Net.getQueryStringValue(keyValues, "seeking");
                if (typeof (genderSeek) !== 'undefined' && genderSeek !== null && genderSeek.length > 0) {
                    PeopleMedia.CP.DefaultGenderSeekID(genderSeek);
                }
                var minAge = PeopleMedia.Net.getQueryStringValue(keyValues, "minage");
                if (typeof (minAge) !== 'undefined' && minAge !== null && minAge.length > 0) {
                    PeopleMedia.CP.DefaultMinAge(minAge);
                }
                var maxAge = PeopleMedia.Net.getQueryStringValue(keyValues, "maxage");
                if (typeof (maxAge) !== 'undefined' && maxAge !== null && maxAge.length > 0) {
                    PeopleMedia.CP.DefaultMaxAge(maxAge);
                }
                var postalCode = PeopleMedia.Net.getQueryStringValue(keyValues, "zipcode");
                if (typeof (postalCode) !== 'undefined' && postalCode !== null && postalCode.length > 0) {
                    if (postalCode.indexOf('%') >= 0) {
                        postalCode = unescape(postalCode);
                    }
                    PeopleMedia.CP.DefaultPostalCode(postalCode);
                }
                var emailAddress = PeopleMedia.Net.getQueryStringValue(keyValues, "email");
                if (typeof (emailAddress) !== 'undefined' && emailAddress !== null && emailAddress.length > 0) {
                    if (emailAddress.indexOf('%') >= 0) {
                        emailAddress = unescape(emailAddress);
                    }
                    PeopleMedia.CP.DefaultEmailAddress(emailAddress);
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "initQueryStringValues" });
            }
        },
        
        initLogging: function () {
            window.onerror = this.handleError;
            PeopleMedia.Diagnostics.registerExceptionHandler(this.handleException);
            _stacktraceScriptLoaded = true;
        },

        tryReady: function () {
            try {
                if (_initComplete && _ready && _stacktraceScriptLoaded) {
                    _readyDelegate.fire();
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"tryReady" });
            }
        },

        onReady: function (handler) {
            _readyDelegate.add(handler);
            this.tryReady();
        },

        ready: function () {
            _ready = true;
            this.tryReady();
        },

        initComplete: function () {
            _initComplete = true;
            this.tryReady();
        },

        initClientConfigComplete: function (ex) {
            _initClientConfigComplete = true;
            _initClientConfigError = (typeof(ex) !== 'undefined' && ex !== null) ? ex : null;
        },

        onClientConfig: function (handler) {
            _clientConfigDelegate.add(handler);

            if (_clientConfig) {
                _clientConfigDelegate.fire();
            }
        },

        clientConfig: function () {
            _clientConfig = true;
            _clientConfigDelegate.fire();
        },

        ui_busy: function () {
            $jq('BODY').addClass('cp_working');
        },

        ui_done: function () {
            $jq('BODY').removeClass('cp_working');
        },

        getAsset: function (path) {
            return self.CpServer() + path;
        },

        getStackTrace: function(exception) {
            try {
                if (typeof (exception) !== 'undefined' && exception != null && typeof (printStackTrace) !== 'undefined') {
                    return printStackTrace({ e: exception, guess: true });
                }
            }
            catch (ex) {
            }
            return "";
        },

        getDetailString: function (detail) {
            var result;
            try {
                if (typeof (detail) === 'undefined' || detail === null) {
                    result = "";
                } else if (typeof (JSON) !== 'undefined') {
                    result = JSON.stringify(detail);
                } else {
                    result = detail;
                }
            }
            catch (ex) {
                result = "";
            }
            return result;
        },

        formatErrorMessage: function (message) {
            try {
                if (typeof (message) !== 'undefined' && message != null) {
                    return message.substr(0, 200);
                }
            }
            catch (ex) {
            }
            return "";
        },

        formatStackTrace: function (stacktrace) {
            try {
                if (typeof (stacktrace) !== 'undefined' && stacktrace != null) {
                    return encodeURI(stacktrace.join('\n')).substr(0, 1000);
                }
            }
            catch (ex) {
            }
            return "";
        },

        formatDetailString: function (detailString) {
            try {
                if (typeof (detailString) !== 'undefined' && detailString != null) {
                    return encodeURI(detailString);
                }
            }
            catch (ex) {
            }
            return "";
        },

        handleException: function (exception, detail) {
            try {
                var stacktrace = "";
                var message = "";
                var exceptionTypeName = "";
                var url = "";
                var lineNumber = 0;
                if (typeof (exception) !== 'undefined' && exception != null) {
                    message = exception.message ? exception.message : ((typeof (exception) === 'string') ? exception : "");
                    exceptionTypeName = exception.name ? exception.name : "";
                    url = exception.fileName ? exception.fileName : "";
                    lineNumber = exception.lineNumber ? exception.lineNumber : 0;
                    stacktrace = PeopleMedia.CP.getStackTrace(exception);
                }
                PeopleMedia.CP._logException("LPS Client", message, exceptionTypeName, url, lineNumber, stacktrace, detail, null);
            }
            catch (ex) {
            }
        },

        handleError: function (message, url, lineNumber) {
            try {
                PeopleMedia.CP._logException("LPS Client Unknown", message, "", url, lineNumber, null, "", null);
            }
            catch (ex) {
            }
        },

        logAjaxError: function (message, url, detail, jqXHR, textStatus, errorThrown, completeFunction) {
            try {
                // don't try to log for these urls
                if (url.indexOf('/v3/lps/api/Log') < 0 && url.indexOf('/v3/log/logexception') < 0 && url.indexOf('/v3/ajax/RefreshSession') < 0) {
                    try {
                        // update detail
                        if (typeof(detail) === 'undefined' || detail == null) {
                            detail = {};
                        }
                        if (textStatus) {
                            detail.textStatus = textStatus;
                        }
                        if (errorThrown) {
                            detail.errorThrown = errorThrown;
                        }
                        if (jqXHR) {
                            if (jqXHR.readyState) {
                                detail.readystate = jqXHR.readyState;
                            }
                            if (jqXHR.status) {
                                detail.jqXHRStatus = jqXHR.status;
                            }
                            if (jqXHR.statusText) {
                                detail.jqXHRStatusText = jqXHR.statusText;
                            }
                            if (jqXHR.responseText) {
                                detail.jqXHRResponseText = jqXHR.responseText.substr(0, 1000);
                            }
                        }
                        if (!detail.pagePath) {
                            detail.pagePath = PeopleMedia.CP.PagePath();
                        }
                        if (!detail.pageVersion) {
                            detail.pageVersion = PeopleMedia.CP.PageVersion();
                        }
                        if (!detail.href) {
                            detail.href = window.location.href;
                        }
                    }
                    catch (ex) {
                    }
                    PeopleMedia.CP._logExceptionPost("LPS Client", message, "", url, 0, null, detail, completeFunction);
                }
            }
            catch (ex) {
            }
        },

        logMessage: function (message, detail, completeFunction) {
            try {
                var url = window.location.href;
                var detailString = PeopleMedia.CP.getDetailString(detail);
                var timeoutValue = 30000;
                PeopleMedia.CP.Services.invoke({
                    method: 'LogMessage',
                    dataType: 'json',
                    data: {
                        "message": PeopleMedia.CP.formatErrorMessage(message),
                        "url": url,
                        "additionalInfo": PeopleMedia.CP.formatDetailString(detailString),
                        "SkipCSSVerif": "HTMLEditor"
                    },
                    success: function (result) {
                        try {
                            if (result && result.redirect) {
                                location.href = result.redirect;
                            }
                        }
                        catch (ex) {
                        }
                    },
                    async: true,
                    timeout: timeoutValue,
                    complete: completeFunction
                });
            }
            catch (ex) {
            }
        },

        logException: function (message, exceptionTypeName, url, detail, completeFunction) {
            PeopleMedia.CP._logException("LPS Client", message, exceptionTypeName, url, 0, null, detail, completeFunction);
        },
        
        _logException: function (appName, message, exceptionTypeName, url, lineNumber, stacktrace, detail, completeFunction) {
            try {
                var detailString = PeopleMedia.CP.getDetailString(detail);
                if (stacktrace == null) {
                    stacktrace = [];
                }
                url = url == "" ? window.location.href : url;
                lineNumber = lineNumber != undefined && lineNumber != null ? lineNumber : 0;
                for (var i = 0; i < stacktrace.length; ++i) {
                    stacktrace[i] = 'at ' + stacktrace[i];
                }
                var timeoutValue = 30000;
                PeopleMedia.CP.Services.invoke({
                    method: 'LogExceptionV2',
                    dataType: 'json',
                    data: {
                        "appName": appName,
                        "message": PeopleMedia.CP.formatErrorMessage(message),
                        "exceptionTypeName": exceptionTypeName,
                        "url": url,
                        "lineNumber": lineNumber,
                        "stacktrace": PeopleMedia.CP.formatStackTrace(stacktrace),
                        "additionalInfo": PeopleMedia.CP.formatDetailString(detailString),
                        "SkipCSSVerif": "HTMLEditor"
                    },
                    success: function (result) {
                        try {
                            if (result && result.redirect) {
                                location.href = result.redirect;
                            }
                        }
                        catch (ex) {
                        }
                    },
                    async: true,
                    timeout: timeoutValue,
                    complete: completeFunction
                });
            }
            catch (ex) {
            }
        },

        _logExceptionPost: function (appName, message, exceptionTypeName, url, lineNumber, stacktrace, detail, completeFunction) {
            try {
                var detailString = PeopleMedia.CP.getDetailString(detail);
                if (stacktrace == null) {
                    stacktrace = [];
                }
                url = url == "" ? window.location.href : url;
                lineNumber = lineNumber != undefined && lineNumber != null ? lineNumber : 0;
                for (var i = 0; i < stacktrace.length; ++i) {
                    stacktrace[i] = 'at ' + stacktrace[i];
                }
                var timeoutValue = 30000;
                jQuery.ajax({
                    type: "POST",
                    url: "/v3/log/logexception",
                    data: { 
                        "appName": appName, 
                        "message": PeopleMedia.CP.formatErrorMessage(message),
                        "exceptionTypeName": exceptionTypeName, 
                        "url": url,
                        "lineNumber": lineNumber,
                        "stacktrace": PeopleMedia.CP.formatStackTrace(stacktrace),
                        "additionalInfo": PeopleMedia.CP.formatDetailString(detailString),
                        "SkipCSSVerif": "HTMLEditor"
                    },
                    dataType: "json",
                    success: function (result) {
                        try {
                            if (result && result.redirect) {
                                location.href = result.redirect;
                            }
                        }
                        catch (ex) {
                        }
                    },
                    async: true,
                    cache: false,
                    timeout: timeoutValue,
                    complete: completeFunction
                });
            }
            catch (ex) {
            }
        },

        addEnterKeyAction: function (containerName, targetName) {
            try {
                var btn = $jq('#' + targetName);
                btn.parents('#' + containerName).keypress(
                    function (e) {
                        try {
                            if (e.which == 13 && e.target.type != 'textarea') {
                                btn.each(
                                    function (index, element) {
                                        try {
                                            var visible = true;
                                            var b = $jq(element);
                                            b.parents(':hidden').each(function (index, parent) {
                                                visible = false;
                                            });
                                            if (visible) {
                                                b.trigger('click');
                                            }
                                        }
                                        catch (ex) {
                                            PeopleMedia.CP.handleException(ex);
                                        }
                                    });
                                return false;
                            }
                        }
                        catch (ex) {
                            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"addEnterKeyAction enter keypress" });
                        }
                    });
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"addEnterKeyAction" });
            }
        },

        getSiteUrl: function (path, currentQueryString) {
            try {
                var basePath = PeopleMedia.Net.getUrlWithoutQueryString(path);
                var qsPath = PeopleMedia.Net.getQueryStringFromUrl(path);
                var qs = '';

                var domainName = PeopleMedia.Net.getDomainName(PeopleMedia.CP.DomainName()).toLowerCase();
                var sessionId = PeopleMedia.CP.SessionId();
                var visitorId = PeopleMedia.CP.VisitorID();
                var subdomain = PeopleMedia.CP.Subdomain();

                if (domainName.split('.').length <= 2) {
                    domainName = subdomain + "." + domainName;
                }

                var qsPathKeyValues = PeopleMedia.Net.parseQueryString(qsPath);
                qsPath = PeopleMedia.Net.createQueryString(qsPathKeyValues, ['CPSessionID', 'VisitorID']);
                if (qsPath.length > 0 && (qsPath.charAt(0) == '?' || qsPath.charAt(0) == '&')) {
                    qsPath = qsPath.substring(1);
                }
                var reservedKeys = PeopleMedia.Net.getQueryStringKeys(qsPathKeyValues);
                reservedKeys.push('cpp', 'CPSessionID', 'VisitorID', 'notrack');

                // load current queryString into collection (or use currentQueryString parameter to override current querystring)
                var qsCurrentKeyValues = PeopleMedia.Net.getQueryString(currentQueryString);
                var qsCurrent = PeopleMedia.Net.createQueryString(qsCurrentKeyValues, reservedKeys);
                if (typeof (sessionId) !== 'undefined' && sessionId !== null) {
                    qsCurrent = PeopleMedia.Net.addQueryStringValue(qsCurrent, "CPSessionID", sessionId);
                }
                if (typeof (visitorId) !== 'undefined' && visitorId !== null) {
                    qsCurrent = PeopleMedia.Net.addQueryStringValue(qsCurrent, "VisitorID", visitorId);
                }
                if (qsCurrent.length > 0 && (qsCurrent.charAt(0) == '?' || qsCurrent.charAt(0) == '&')) {
                    qsCurrent = qsCurrent.substring(1);
                }

                // get merged querystrings
                if (qsPath.length > 0 || qsCurrent.length > 0) {
                    qs = '?' + ((qsPath.length > 0) ? qsPath : '') + ((qsPath.length > 0 && qsCurrent.length > 0) ? '&' : '') + qsCurrent;
                }

                // remove host and domain from basePath
                var protocolIndex = basePath.indexOf('://');
                if (protocolIndex >= 0 || basePath.substring(0, subdomain.length + 1).toLowerCase() == (subdomain + '.')) {
                    var baseStart = (protocolIndex >= 0) ? (protocolIndex + 3) : 0;
                    var slashStart = basePath.indexOf('/', baseStart);
                    if (slashStart >= 0) {
                        basePath = basePath.substring(slashStart + 1);
                    } else {
                        basePath = "";
                    }
                }
                return "http://" + domainName + ((basePath.length > 0 && basePath.charAt(0) != '/') ? '/' : '') + basePath + qs;
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getSiteUrl" });
                return "http://" + PeopleMedia.CP.DomainName();
            }
        },

        gotoSite: function (path, queryString) {
            try {
                window.location.href = this.getSiteUrl(path, queryString);
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"gotoSite" });
            }
        },

        getCpUrl: function (cpPage, queryString) {
            var path;
            try {
                path = "/v3/lps?cpp=" + ((typeof(cpPage) !== 'undefined' && cpPage !== null) ? cpPage : "");
                return this.getSiteUrl(path, queryString);
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getCpUrl" });
                return path;
            }
        },

        gotoCPPage: function (cpPage, queryString) {
            try {
                var path = this.getCpUrl(cpPage, queryString);
                window.location.href = path;
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"gotoCPPage" });
            }
        },

        convertGenderToID: function (gender) {
            try {
                if (typeof (gender) !== 'undefined' && gender !== null) {
                    if (gender === 1 || gender === 2) {
                        return gender;
                    }
                    var genderLower = gender.toString().toLowerCase();
                    if (genderLower === "1" || genderLower === "m" || genderLower === "male") {
                        return 1;
                    }
                    if (genderLower === "2" || genderLower === "f" || genderLower === "female") {
                        return 2;
                    }
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "convertGenderToID" });
            }
            return null;
        },

        isValidMemberId: function() {
            try {
                return (PeopleMedia.CP.MemberID() !== null && PeopleMedia.CP.MemberID() > 0);
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "isValidMemberId" });
                return false;
            }
        },

        authenticateRegisteredMembers: function (completeFunction) {
			
            try {
                PeopleMedia.CP.Services.invoke({
                    verb: 'POST',
                    method: 'AuthenticateWithPersistentLogin',
                    data: { },
                    async: false,
                    success: function (response) {
                        if (response && response.redirect) {
                            location.href = response.redirect;
                        } else {
                            if (response && response.status === "Success") {
                                if (response.memberId) {
                                    PeopleMedia.CP.MemberID(response.memberId);
                                }
                                if (response.encMemberId) {
                                    PeopleMedia.CP.EncodedMemberID(response.encMemberId);
                                }
                                if (response.gender) {
                                    PeopleMedia.CP.GenderID(response.gender);
                                }
                                if (response.seeking) {
                                    PeopleMedia.CP.GenderSeekID(response.seeking);
                                }
                            }
                        }
                    },
                    complete: completeFunction
                });
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "authenticateRegisteredMembers" });
            }
        }
    };

    return self;
} ();



PeopleMedia.CP.Delegate = function (context, handler) {
    var _context = context;
    var _handler = handler;
    return {
        invoke: function () {
            return _handler.apply(_context, arguments);
        }
    };
};

PeopleMedia.CP.MulticastDelegate = function () {
    var _handlers = [];
    return {
        addHandler: function (handler) {
            if (handler == null) {
                return;
            }
            _handlers.push(handler);
        },
        removeHandler: function (handler) {
            if (handler == null) {
                return;
            }
            for (var i=0; i<_handlers.length; ++i) {
                if (_handlers[i] == handler) {
                    _handlers.splice(i, 1);
                    break;
                }
            }
        },
        invoke: function () {
            var result;
            var results = [];
            for (var i = 0; i < _handlers.length; ++i) {
                var handler = _handlers[i];
                if (typeof (handler) == "PeopleMedia.CP.Delegate") {
                    result = handler.invoke(arguments);
                    if (typeof (result) !== "undefined") {
                        results.push(result);
                    }
                } else if (typeof (handler) == "function") {
                    result = handler.apply(null, arguments);
                    if (typeof (result) !== "undefined") {
                        results.push(result);
                    }
                }
            }
            return results;
        }
    };
};


PeopleMedia.CP.Services = function() {
    var _proxy = null;
    
    return {
        persistCookies : function (response) {
            if (response.Cookies) {
                for (var key in response.Cookies) {
                    PeopleMedia.Net.createCookie(key, response.Cookies[key], 30);
                }
            }
        },
        
        invoke : function (opts) {
            if (_proxy == null) {
                _proxy = new PeopleMedia.ServiceProxy(PeopleMedia.Application.resolveUrl(PeopleMedia.CP.LpsApiUrl()));
            }
            _proxy.invoke(opts);
        }
    };
}();


PeopleMedia.CP.Messaging = function () {
    var _messages = null;
    var _onShowMessages = new PeopleMedia.CP.MulticastDelegate();

    var hasMessageSummary = function () {
        return $jq('.errorMessageSummary').length > 0;
    };

    var getMessageSummary = function () {
        return $jq('.errorMessageSummary');
    };

    var hasFieldLevelError = function (fieldName) {
        return $jq('.error_' + fieldName).length > 0;
    };

    var getFieldLevelError = function (fieldName) {
        return $jq('.error_' + fieldName).filter('.fieldError');
    };

    return {
        Oid: "PeopleMedia.CP.Messaging",
        addOnShowMessages: function (handler) {
            _onShowMessages.addHandler(handler);
        },

        removeOnShowMessages: function (handler) {
            _onShowMessages.removeHandler(handler);
        },

        reset: function () {
            try {
                if (hasMessageSummary) {
                    getMessageSummary().html('');
                    getMessageSummary().hide();
                    //getMessageSummary().fadeTo('fast', '1.0');
                }

                $jq('.fieldError').each(function () {
                    $jq(this).hide();
                });

                if (_messages) {
                    for (var i = 0; i < _messages.length; i++) {
                        var field = $jq('input[name="' + _messages[i].Field + '"]')[0];
                        var label = $jq('label[for="' + _messages[i].Field + '"]')[0];

                        $jq(label).removeClass('invalidFieldLabel');
                        $jq(field).removeClass('invalidField');
                    }
                }

                _messages = null;
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"reset" });
            }
        },

        show: function (messages) {
            try {
                _onShowMessages.invoke(messages);

                this.reset();

                _messages = messages;

                if (hasMessageSummary()) {
                    getMessageSummary().html('<ul></ul>');
                    getMessageSummary().show();
                }

                for (var i = 0; i < messages.length; i++) {
                    if (messages[i].Field) {
                        var field = $jq('input[name="' + messages[i].Field + '"]');
                        var label = $jq('label[for="' + messages[i].Field + '"]');

                        label.addClass('invalidFieldLabel');
                        field.addClass('invalidField');
                        if (i == 0 && field.length > 0) {
                            field.focus();
                        }
                        if (hasFieldLevelError(messages[i].Field)) {
                            var fieldError = getFieldLevelError(messages[i].Field);

                            fieldError.html(messages[i].Text);
                            fieldError.show();
                        }
                    }

                    if (hasMessageSummary()) {
                        $jq('UL', getMessageSummary()).append('<li>' + messages[i].Text + '</li>');
                    }
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"show" });
            }
        },

        showEmailError: function (messages) {
            try {
                this.reset();

                _messages = messages;

                if (hasMessageSummary()) {
                    getMessageSummary().html('<ul></ul>');
                    getMessageSummary().show();
                }

                for (var i = 0; i < messages.length; i++) {
                    if (messages[i].Field) {
                        var field = $jq('input[name="' + messages[i].Field + '"]');
                        var label = $jq('label[for="' + messages[i].Field + '"]');

                        label.addClass('invalidFieldLabel');
                        field.addClass('invalidField');
                        if (i == 0 && field.length > 0) {
                            field[0].focus();
                        }
                    }

                    if (hasMessageSummary())
                        $jq('UL', getMessageSummary()[0]).append('<li><p class="emailerror">' + messages[i].Text + '</p><p class="emailyes">Yes</p><input id="correctEmailAddressChkBox" name="" type="checkbox" value="" class="emailsavecheck"></li>');
                }
            }
            catch (ex) {
                PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"showEmailError" });
            }
        },

        dim: function () {
            try {
                if (hasMessageSummary) {
                    getMessageSummary().fadeTo('slow', '0.3');
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"dim" });
            }
        }
    };
} ();


PeopleMedia.CP.Resources = function () {
    var _resources = [];

    var getResource = function (name) {
        try {
            var url = PeopleMedia.CP.CpResourceRoot() + name + '.xml';
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:"PeopleMedia.CP.Resources", method:"getResource" });
        }
    };
        
    return {
        Oid: "PeopleMedia.CP.Resources",
        LoginMessages: function () {
            try {
                return getResource('LoginMessages');
           }
           catch (ex) {
               PeopleMedia.CP.handleException(ex, { oid:this.Oid, method: "LoginMessages" });
           }
        }
    };
} ();


PeopleMedia.CP.StatefulPane = {
    Oid: "PeopleMedia.CP.StatefulPane",
    init: function () {
        $jq('.cp_stateful').each(function() {
            try {
                var loginView = $jq('.loginView', this);
                var registerView = $jq('.registerView', this);

                var mrid = PeopleMedia.Net.readCookie('MRID');
                var hasLoggedIn = mrid != undefined && mrid != null && mrid.length > 0;
                if ( hasLoggedIn ) {
                    registerView.fadeOut('fast', function() {
                        loginView.fadeIn('slow');
                    });
                }
                else {
                    loginView.fadeOut('fast', function() {
                        registerView.fadeIn('slow');
                    });
                }
            
                $jq("[class $= 'View']").each(function() {
                    var view = this;

                    $jq('.switchToLoginView', view).each(function() {
                        if (loginView.length > 0) {
                            $jq(this).bind('click', function() {
                                PeopleMedia.CP.ui_busy();

                                $jq(view).fadeOut('fast', function() {
                                    PeopleMedia.CP.Messaging.reset();
                                    loginView.fadeIn('slow');
                                    PeopleMedia.CP.ui_done();
                                });
                            });
                        }
                    });

                    $jq('.switchToRegisterView', view).each(function() {
                        if (registerView.length > 0) {
                            $jq(this).bind('click', function() {
                                PeopleMedia.CP.ui_busy();
                                $jq(view).fadeOut('fast', function() {
                                    PeopleMedia.CP.Messaging.reset();
                                    registerView.fadeIn('slow');
                                    PeopleMedia.CP.ui_done();
                                });
                            });
                        }
                    });
                });
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"init" });
            }
        });
    }
};

PeopleMedia.CP.Utilities = function () {
    return {
        Oid: "PeopleMedia.CP.Utilities",
        dateStringToDate: function (dtString) {
            /// <summary>Converts a JSON ISO or MSAJAX string into a date object</summary>    
            /// <param name="dtString" type="String">Date string to convert</param>
            /// <returns type="Date" mayBeNull="true">Javascript Date or null if invalid date</returns>
            try {
                var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
                var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
                var a = reISO.exec(dtString);
                if (a) {
                    return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
                }
                a = reMsAjax.exec(dtString);
                if (a) {
                    var b = a[1].split("-");
                    if (a[1].charAt(0) == '-') {
                        return new Date(-b[1]);
                    } else {
                        return new Date(+b[0]);
                    }
                }
            } catch(ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"dateStringToDate" });
            }
            return null;
        },

        formatDateMMDDYYYY: function (date) {
            /// <summary>Return age in years between start date and end date</summary>
            /// <param name="date" type="Object">Date object</param>
            /// <returns type="string">Date formatted as MM/DD/YYYY</returns>
            try {
                if (date && date.getMonth && date.getDate && date.getFullYear) {
                    return ((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear());
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"formatDateMMDDYYYY" });
            }
            return "";
        },

        formatDateYYYYMMDD: function (date) {
            /// <summary>Return age in years between start date and end date</summary>
            /// <param name="date" type="Object">Date object</param>
            /// <returns type="string">Date formatted as MM/DD/YYYY</returns>
            try {
                if (date && date.getMonth && date.getDate && date.getFullYear) {
                    var year = date.getFullYear().toString();
                    var month = (date.getMonth() + 1).toString();
                    month = (month.length > 1) ? month : '0' + month;
                    var day = date.getDate().toString();
                    day = (day.length > 1) ? day : '0' + day;
                    return year + '-' + month + '-' + day;
                }
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "formatDateYYYYMMDD" });
            }
            return "";
        },

        calculateAgeInYears: function (startDate, endDate) {
            /// <summary>Return age in years between start date and end date</summary>
            /// <param name="startDate" type="Object">Starting Date object (e.g. birthdate)</param>
            /// <param name="endDate" type="Object" optional="true">Ending Date object (uses current date if not specified)</param>
            /// <returns type="Number" integer="true" mayBeNull="true">Age in years or null if there is an exception</returns>
            try {
                if (arguments.length === 0 || typeof (startDate) === 'undefined' || startDate == null || !startDate.getMonth || !startDate.getDate || !startDate.getFullYear) {
                    return null;
                }
                // use current date for endDate if it is missing or not a Date object
                var end = (arguments.length > 1 && typeof (endDate) !== 'undefined' && endDate != null && endDate.getMonth && endDate.getDate && endDate.getFullYear) ? endDate : new Date();
                var age = end.getFullYear() - startDate.getFullYear();
                if (end.getMonth() < startDate.getMonth() || (end.getMonth() == startDate.getMonth() && end.getDate() < startDate.getDate())) {
                    age--;
                }
                return age;
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"calculateAgeInYears" });
                return null;
            }
        },

        isNullOrWhiteSpace: function (str) {
            try {
                if (typeof (str) === 'undefined' || str === null) {
                    return true;
                }
                return !/\S/.test(str);
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "isNullOrWhiteSpace" });
            }
        },

        isGuid: function (str) {
            try {
                var regex = new RegExp(/^([0-9a-fA-F]){8}(-([0-9a-fA-F]){4}){3}-([0-9a-fA-F]){12}$/);
                return regex.test(str);
            }
            catch (ex) {
                PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "isGuid" });
            }
        }
    };
}();

// load these before $jq(document).ready
(function () {
    try {
        PeopleMedia.CP.initLogging();
        PeopleMedia.CP.init();
    }
    catch (ex) {
        PeopleMedia.CP.handleException(ex, { oid: "lps_main module", method: "CP init" });
    }
})();

$jq(document).ready(function () {
    try {
        // try initClientConfig again if it hasn't completed
        if (!PeopleMedia.CP.IsInitClientConfigComplete() && PeopleMedia.CP.initClientConfig && Object.prototype.toString.call(PeopleMedia.CP.initClientConfig) === '[object Function]') {
            PeopleMedia.CP.initClientConfig();
        }
        // run other delegated functions associated with onClientConfig
        PeopleMedia.CP.clientConfig();
        PeopleMedia.CP.StatefulPane.init();
        PeopleMedia.CP.ready();
    }
    catch (ex) {
        PeopleMedia.CP.handleException(ex, { oid: "lps_main document ready", method: "CP setup" });
    }
});